import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:keyboard_utils_fork/keyboard_listener.dart' as key_listener;
import 'package:keyboard_utils_fork/keyboard_utils.dart';
import '../../../../bean/opetation_detail.dart';
import '../../../../config/ApiConfig.dart';
import '../../../../http/DioClient.dart';
import '../../../../http/core/ResponseData.dart';
import '../../../../util/HDNavigator.dart';
import '../../../../util/LoadingUtils.dart';
import 'state.dart';

class AddOperationLogic extends GetxController {
  final AddOperationState state = AddOperationState();
  KeyboardUtils _keyboardUtils = KeyboardUtils();
  int _idKeyboardListener = 0;

  @override
  void onReady() {
    super.onReady();
    super.onReady();
    _idKeyboardListener = _keyboardUtils.add(
        listener: key_listener.KeyboardListener(
            willHideKeyboard: () {
              FocusManager.instance.primaryFocus?.unfocus();
            },
            willShowKeyboard: (d) {}));
  }

  @override
  void onClose() {
    super.onClose();
    _keyboardUtils.unsubscribeListener(subscribingId: _idKeyboardListener);
    if (_keyboardUtils.canCallDispose()) {
      _keyboardUtils.dispose();
    }
  }

  /// 列表刷新，isRefresh：true是刷新，false加载更多
  Future<List<OperationBean>> requestList(
      {String? selectedType, String? searchKey}) async {
    Map<String, dynamic> data = {
      "pageNum": 1,
      "pageSize": 10,
    };
    data["customerName"] = searchKey;
    ResponseData responseData = await DioClient().doPost(
        ApiConfig.queryCustomerUrl,
        data: data,
        options: Options(extra: {"hideLoading": true}));
    LoadingUtils.dismiss();
    if (responseData.isok) {
      dynamic result = OperationDetail.fromJson(responseData.data);
      state.dataList.clear();
      state.dataList.addAll(result.list ?? []);
    }
    return state.dataList;
  }

  Future<void> submit() async {
    state.addOperation.status = 0;
    state.addOperation.customerInfoId = state.operationBean.customerInfoId;
      if((state.operationBean.phoneNumber??"").isEmpty){
        LoadingUtils.showToast("请填入客户信息");
        return;
      }
      state.addOperation.phoneNumber = state.operationBean.phoneNumber;
      state.addOperation.address = state.operationBean.address;
      state.addOperation.buildingAddress = state.operationBean.buildingAddress;
      state.addOperation.faultDescription = state.operationBean.faultDescription;
      ResponseData response = await DioClient()
          .doPost(ApiConfig.saveOperationUrl, data: state.addOperation);
      if (response.isok) {
        if (response.code == "0") {
          LoadingUtils.showToast(response.msg ?? "新增成功");
          HDNavigator.close(result: "refresh");
        } else {
          LoadingUtils.showToast(response.msg ?? "新增失败");
        }
      } else {
        LoadingUtils.showToast(response.msg ?? "新增失败");
      }
    }

}
